package com.lnsoft.cac.server.handle;

import com.lnsoft.cac.server.handle.codec.*;
import com.lnsoft.cac.server.handle.threadpools.ServiceInvokePools;
import com.lnsoft.cac.server.util.*;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class CACChannelHandle extends ChannelInboundHandlerAdapter {

    private Device device;
    private ServiceInvokePools invokePools;
    private CACGlobalData cacGlobalData;

    public CACChannelHandle(Device device, ServiceInvokePools invokePools,CACGlobalData cacGlobalData){
        this.device = device;
        this.invokePools = invokePools;
        this.cacGlobalData = cacGlobalData;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try{
            if (msg == null) {
                return;
            }


            I1Frame decFrame = (I1Frame)msg;

            // 交由自定义线程池处理
            invokePools.executeHandleFrame(ctx,decFrame, device);

        }catch (Exception e){
            log.error("channelRead error!!",e);
            throw e;
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("新连接接入 >>> channel-id：" +  ctx.channel().id());
        log.info("本地地址：" + ctx.channel().localAddress().toString());
        log.info("远程地址：" + ctx.channel().remoteAddress().toString());
        //新channel添加到channelgroup
        CACGlobalData.channelGroup.add(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        //channel 从 channelgroup 删除
        CACGlobalData.channelGroup.remove(ctx.channel());

        log.info(ctx.channel().id() + " " +ctx.channel().localAddress().toString() + "已断开");
        //  标记装置离线
        device.setChannelId(null);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }
    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        log.warn("客户端{}{}断开执行清理工作", device.getClientId(), device.getServerPort());
        //  执行断开连接
        ctx.channel().close();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("channel:{} 发生 handle 异常: {}",ctx.channel().id(),cause.toString());
        ctx.close();
    }
}
